package pers.ycm.nacos.client.controller;

import com.alibaba.nacos.api.annotation.NacosInjected;
import com.alibaba.nacos.api.config.annotation.NacosValue;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;


/**
 * @author yuanchengman
 * @date 2021-09-17
 */
@RestController
public class HomeController {

    @NacosValue(value = "${log.level}", autoRefreshed = true)
    private String logLevel;

    @NacosInjected
    private NamingService namingService;

    @GetMapping("test/invoke")
    public String invoke() {
        return LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
    }

    @GetMapping("loglevel")
    public String getLogLevel() {
        return logLevel;
    }

    @GetMapping("invoke/provider/a")
    public String invokeProviderA() throws Exception {
        Instance instance = namingService.selectOneHealthyInstance("provider-a");
        RestTemplate template = new RestTemplate();
        String url = String.format("http://%s:%s/test/invoke", instance.getIp(), instance.getPort());
        return template.getForObject(url, String.class);
    }
}
